package com.pgytesting.mobilecertpay.controller;

import com.alibaba.fastjson.JSONObject;
import com.pgytesting.mobilecertpay.entity.InterfaceService;
import com.pgytesting.mobilecertpay.entity.NaBusinessInformation;
import com.pgytesting.mobilecertpay.service.*;
import com.pgytesting.mobilecertpay.util.ResponseMassage;
import com.pgytesting.mobilecertpay.util.UtilMethod;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version v1.0
 * @ProjectName: MobileCertPay
 * @ClassName: MobileCertPayController
 * @Description: TODO(Controller控制层)
 * @Author: sunbo@pgytesting.cn
 * @Date: 2019/3/11 18:10
 */
@Slf4j
@RestController
public class MobileCertPayController {


    /**
     * 发送邮件服务
     */
    @Autowired
    MailService mailService;

    /**
     * token日志信息表(NaUserToken)表服务接口
     */
    @Autowired
    NaUserTokenService naUserTokenService;


    /**
     * 公钥私钥日志表(NaSecret)表服务接口
     */
    @Autowired
    NaSecretService naSecretService;

    /**
     * 银行卡绑定信息(NaBankCard)表服务接口
     */
    @Autowired
    NaBankCardService naBankCardService;

    /**
     * 商户信息表(NaBusinessInformation)表服务接口
     */
    @Autowired
    NaBusinessInformationService naBusinessInformationService;

    /**
     * 验证码信息表(NaCaptchaInformation)表服务接口
     */
    @Autowired
    NaCaptchaInformationService naCaptchaInformationService;

    /**
     * 订单信息表(NaOrderInformation)表服务接口
     */
    @Autowired
    NaOrderInformationService naOrderInformationService;

    /**
     * 用户信息表(NaUserInfo)表服务接口
     */
    @Autowired
    NaUserInfoService naUserInfoService;

    /**
     * 调用生成公钥私钥，和商户ID一一对应 系统传出参数会进行私钥加密并且会对数据进行数字签名，每组数据包含数字签名和加密参数 传进来的参数必须调用公钥进行加密形式为JSON字符串{data:"加密后的字符串"} 1、编写
     */

    @RequestMapping(value = "/gateway.action", method = RequestMethod.GET)
    public Map<String, Object> gePublicEncryption() {
        log.info("非法的GET请求");
        return ResponseMassage.getResMassage("10002");

    }

    /**
     * @param @param [paraMap]
     * @return @return java.util.Map<java.lang.String,java.lang.String>
     * @throws
     * @Title: gePublicEncryption
     * @Description: TODO(接收请求 ， 进行请求转发)
     * @author sunbo@pgytesting.cn
     * @date 2019/1/25 17:46
     */
    @RequestMapping(value = "/gateway.action", method = RequestMethod.POST)
    public Map<String, Object> gePublicEncryption(@RequestBody Map<String, Object> paraMap) {
        log.info("进行参数校验");
        if (!"4.0.0".equals(paraMap.get("version"))) {
            log.info("接口版本校验错误");
            return ResponseMassage.getResMassage("99031");
        }
        JSONObject json = new JSONObject();
        if ((!UtilMethod.isEmpty(String.valueOf(paraMap.get("secId"))) || "RSA".equals(String.valueOf(paraMap.get("secId")))) && String.valueOf(paraMap.get("data")).length() > 0) {
            try {
                json = naSecretService.getDecrypt(paraMap);
                if (json.isEmpty()) {
                    return ResponseMassage.getResMassage("99033");
                }
            } catch (Exception e) {
                return ResponseMassage.getResMassage("99033");
            }
            if (json.isEmpty()) {
                return ResponseMassage.getResMassage("99033");
            }
            json.put("merchantId", paraMap.get("merchantId"));
        } else if(!UtilMethod.isEmpty(String.valueOf(paraMap.get("data"))) && String.valueOf(paraMap.get("data")).length() != 0){
            log.info("加密算法参数缺失");
            return ResponseMassage.getResMassage("99012");
        }
        log.info("转换枚举，进行service转发");
        String service = String.valueOf(paraMap.get("service"));
        if (UtilMethod.isEmpty(service)){
            return ResponseMassage.getResMassage("99027");
        }
        switch (InterfaceService.valueOf(service)) {
            case NEW_APE_WANG_API3_ADD_NEW_MERCHANT:
                if (UtilMethod.isEmpty(String.valueOf(paraMap.get("merchantMail")))) {
                    log.info("缺少注册商户必要参数merchantMail");
                    return ResponseMassage.getResMassage("10000");
                }
                // 新增商户接口
                log.info("新增商户接口");
                json.put("IdCardFront",paraMap.get("IdCardFront"));
                json.put("IdCardNegative",paraMap.get("IdCardNegative"));
                return addNewMerchant(json);
            case NEW_APE_WANG_API3_PREPARE_PAY:
                // 预支付接口
                log.info("预支付接口");
                json.put("IdCardFront",paraMap.get("IdCardFront"));
                json.put("IdCardNegative",paraMap.get("IdCardNegative"));
                return prePayment(json);
            case NEW_APE_WANG_API3_CONFIRM_PAYMENT:
                // 确认支付接口
                log.info("确认支付接口");
                return confirmPayment(json);
            case NEW_APE_WANG_API3_RESEND_SMS_VERIFICATION_CODE:
                // 重发短信验证码接口
                log.info("重发短信验证码接口");
                return ReVerificationCode(json);
            case NEW_APE_WANG_API3_ORDER_STATUS:
                // 查询订单状态
                log.info("查询订单状态");
                return queryOrderStatus(json);
            case NEW_APE_WANG_API3_UNTIED_BANK_CARD:
                // 解绑银行卡
                log.info("解绑银行卡");
                return ResponseMassage.getResMassage("10002");
            case NEW_APE_WANG_API3_QUERY_CARD_BIN:
                // 查询卡bin
                log.info("查询卡bin");
                return queryCard(json);
            case NEW_APE_WANG_API3_BANK_CARD_LIST:
                // 查询支持银行卡列表
                log.info("查询支持银行卡列表");
                return querySupportCardList();
            case NEW_APE_WANG_API3_GET_THE_PUBLIC_KEY:
                // 查询支持银行卡列表
                log.info("获取公钥");
                return RsaEncryption(paraMap);
            case NEW_APE_WANG_API3_GET_ALL_BUSINESS_INFORMATION:
                // 查询支持银行卡列表
                log.info("获取商户信息");
                return queryAllBusinessInf();
            default:
                return ResponseMassage.getResMassage("99021");
        }


    }


    private Map<String, Object> RsaEncryption(Map<String, Object> paraMap) {
        log.info("进行公钥数据获取");
        return naSecretService.queryById(paraMap);
    }


    /**
     * @param @param [paraMap]
     * @return @return @return java.util.Map<java.lang.String,java.lang.String>
     * @throws
     * @Title: dddNewMerchant
     * @Description: TODO(新增商户)
     * @author sunbo@pgytesting.cn
     * @date 2019/1/24 16:09
     */
    private Map<String, Object> addNewMerchant(JSONObject json) {
        Map<String, Object> resultMap = naBusinessInformationService.insert(json);
        if ("00".equals(resultMap.get("respCode"))) {
            JSONObject data = JSONObject.parseObject(String.valueOf(resultMap.get("data")));
            data.get("merchantMail");
            log.info("进行商户注册信息邮件下发");
            String adder = String.valueOf(data.get("merchantMail"));
            String title = "致" + data.get("appName") + "商家的一份注册回执邮件";
            String content = "以下的内容是有关您%s软件的注册信息：%n您APP的中文名：%s%n您的APP ID：%s%n您的商户代码：%s%n登陆请使用注册关联的手机号%s或者邮箱地址%s%n%n%n%n请您一定务必要妥善保存!";
            content = String.format(content, String.valueOf(data.get("appName"))
                    , String.valueOf(data.get("appName"))
                    , String.valueOf(data.get("appId"))
                    , String.valueOf(data.get("merchantId"))
                    , String.valueOf(data.get("mobileNo"))
                    , String.valueOf(data.get("merchantMail")));
            mailService.sendTextMail(adder, title, content);
            log.info("剔除data数据，进行数据返回");
            resultMap.remove("data");
        }
        return resultMap;
    }


    /**
     * @param @param [paraMap]
     * @return @return java.util.Map<java.lang.String,java.lang.String>
     * @throws
     * @Title: prepayment
     * @Description: TODO(预支付)
     * @author sunbo@pgytesting.cn
     * @date 2019/1/24 16:08
     */
    private Map<String, Object> prePayment(JSONObject jsonObject) {
        // 调用订单信息service
        Map<String, Object> resultMap = naOrderInformationService.insert(jsonObject);
        if ("00".equals(String.valueOf(resultMap.get("respCode")))) {
            mailService.sendTextMail(jsonObject.getString("merchantMail"), "支付确认邮件", String.valueOf(resultMap.get("respMsg")));
            resultMap.remove("respCode");
            resultMap.remove("respMsg");
            return ResponseMassage.getResMassage(resultMap);
        }
        return resultMap;
    }


    /**
     * @param @param [paraMap]
     * @return @return java.util.Map<java.lang.String,java.lang.String>
     * @throws
     * @Title: confirmPayment
     * @Description: TODO(确认支付)
     * @author sunbo@pgytesting.cn
     * @date 2019/1/24 16:15
     */
    private Map<String, Object> confirmPayment(JSONObject jsonObject) {
        Map<String, Object> map = naOrderInformationService.update(jsonObject);
        if ("00".equals(map.get("respCode"))){
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("orderStatus", map.get("orderStatus"));
            resultMap.put("outOrderId", map.get("outOrderId"));
            String mag = "尊敬的用户\n"
                    + map.get("realName")
                    + "\t您有一个订单支付成功，订单信息见下：\n\n\t\t订单号(outOrderId)："
                    + map.get("outOrderId")
                    + "\n\t\t金额(amount)："
                    + map.get("amount")
                    + "\n\t\t交易时间(tradeTime)："
                    + UtilMethod.getTime(Long.valueOf(String.valueOf(map.get("tradeTime"))))
                    + "\n\t\t订单状态(orderStatus)："
                    + (map.get("orderStatus").equals("S") ? "成功 " : (map.get("orderStatus").equals("I") ? "处理中 " : (map.get("orderStatus").equals("F") ? "失败 " : "未支付")));
            mailService.sendTextMail(String.valueOf(map.get("merchantMail")), "支付结果通知邮件", mag);
            return ResponseMassage.getResMassage(resultMap);
        }
        return map;
    }


    /**
     * @param @param [paraMap]
     * @return @return java.util.Map<java.lang.String,java.lang.String>
     * @throws
     * @Title: ReVerificationCode
     * @Description: TODO(重发短信验证码)
     * @author sunbo@pgytesting.cn
     * @date 2019/1/24 16:19
     */
    private Map<String, Object> ReVerificationCode(JSONObject jsonObject) {
        Map<String, Object> resultMap = naCaptchaInformationService.insert(jsonObject);
        if ("200".equals(String.valueOf(resultMap.get("respCode")))) {
            mailService.sendTextMail(String.valueOf(resultMap.get("merchantMail")), "验证信息", String.valueOf(resultMap.get("respMsg")));
            return ResponseMassage.getResMassage("00");
        } else {
            return ResponseMassage.getResMassage("20007");
        }
    }


    /**
     * @param @param [paraMap]
     * @return @return java.util.Map<java.lang.String,java.lang.String>
     * @throws
     * @Title: queryOrderStatus
     * @Description: TODO(查询订单状态)
     * @author sunbo@pgytesting.cn
     * @date 2019/1/24 16:27
     */
    private Map<String, Object> queryOrderStatus(JSONObject jsonObject) {
        return naOrderInformationService.queryById(jsonObject);
    }


    /**
     * @param @param [paraMap]
     * @return @return java.util.Map<java.lang.String,java.lang.String>
     * @throws
     * @Title: untiedBankCard
     * @Description: TODO(解绑银行卡)
     * @author sunbo@pgytesting.cn
     * @date 2019/1/24 16:31
     */
    public Map<String, Object> untiedBankCard(JSONObject jsonObject) {
        return null;
    }


    /**
     * @param @param [paraMap]
     * @return @return java.util.Map<java.lang.String,java.lang.String>
     * @throws
     * @Title: queryCard
     * @Description: TODO(查询卡bin)
     * @author sunbo@pgytesting.cn
     * @date 2019/1/24 16:32
     */
    private Map<String, Object> queryCard(JSONObject jsonObject) {
        return ResponseMassage.getResMassage(UtilMethod.getBackCardInf(jsonObject.getString("bankCardNo")));
    }


    /**
     * @param @param [paraMap]
     * @return @return java.util.Map<java.lang.String,java.lang.String>
     * @throws
     * @Title: querySupportCardList
     * @Description: TODO(查询支持银行卡列表)
     * @author sunbo@pgytesting.cn
     * @date 2019/1/24 16:34
     */
    private Map<String, Object> querySupportCardList() {
        return ResponseMassage.getResMassage(UtilMethod.getBackCardList());
    }


    /**
     * @Title: queryAllBusinessInf
     * @Description: TODO(查询所有商户信息)
     * @param @param
     * @return @return
     * @author sunbo@pgytesting.cn
     * @throws
     * @date 2019/5/24 8:57
     */
    private Map<String,Object> queryAllBusinessInf(){
        List<Map<String,Object>> resultMap = naBusinessInformationService.queryAll(new NaBusinessInformation());
        return ResponseMassage.getResMassage(resultMap);
    }

}
